<template>
  <div class="image-container">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header" v-if="!isSel">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>素材管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- card body -->
      <!-- 操作 -->
      <div class="image-todo">
        <el-radio-group size="small" v-model="status" @change="changeStatus">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
        <!-- 图片选择按钮 -->
        <el-button
          v-if="!isSel"
          @click="dialogVisible = true"
          size="small"
          type="success"
          >上传图片素材</el-button
        >
        <el-button v-else @click="selOk" size="small" type="success"
          >确定</el-button
        >
      </div>
      <!-- 素材列表 -->
      <el-row :gutter="10">
        <el-col
          v-for="(img, i) in images"
          :key="img.id"
          :xs="12"
          :sm="6"
          :md="6"
          :lg="4"
          @click.native="selImg(img)"
        >
          <div class="image-box">
            <el-image :src="img.url" fit="fill"></el-image>
            <!-- 图片操作 -->
            <div class="image-act">
              <span
                class="el-icon-star-on"
                :style="{ color: img.is_collected ? '#FFD04B' : 'white' }"
                @click="collectImg(img)"
              ></span>
              <span class="el-icon-delete" @click="delImg(img.id, i)"></span>
            </div>
            <!-- 图片选择 -->
            <div class="image-sel" v-if="img.isSelected">
              <i class="el-icon-success"></i>
            </div>
          </div>
        </el-col>
      </el-row>
      <!-- 分页 -->
      <el-pagination
        background
        @current-change="pageChange"
        layout="prev, pager, next,total"
        :per_size="this.per_page"
        :total="this.total"
      >
      </el-pagination>
    </el-card>
    <!-- 上传 -->
    <el-dialog
      title="上传素材"
      append-to-body
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-upload
        class="avatar-uploader"
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        name="image"
        :headers="headers"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { getImages, switchCollect, deleteImage } from '@/api/image'
import { getToken } from '@/utils/store'
export default {
  props: {
    // 选择素材模式
    isSel: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // 当前选中的图片
      curSeledImg: '',
      // 上传图片地址
      imageUrl: '',
      headers: {
        Authorization: `Bearer ${getToken().token}`
      },
      // 是否显示上传
      dialogVisible: false,
      // 图片状态
      status: false,
      // 素材列表
      images: [],
      // 分页数据
      // 当前页
      page: 1,
      per_page: 12,
      total: 0
    }
  },
  created () {
    this.getImages()
  },
  methods: {
    // 确认选择
    selOk () {
      this.$emit('selected', this.curSeledImg)
    },
    // 图片选择
    selImg (img) {
      if (this.isSel) {
        // 重置之前选择的
        this.images.forEach((img) => (img.isSelected = false))
        img.isSelected = true
        // 存储选中图片
        this.curSeledImg = img.url
      }
    },
    // 上传
    handleAvatarSuccess (res, file) {
      console.log(res, file, URL.createObjectURL(file.raw))
      this.imageUrl = URL.createObjectURL(file.raw)
      this.page = 1
      this.status = false
      // 上传成功关闭弹出层
      this.dialogVisible = false
      this.imageUrl = ''
      this.$message.success('上传素材成功')
      this.getImages()
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 删除图片
    async delImg (id, i) {
      try {
        await deleteImage(id)
        this.$message.success('删除成功！')
        this.images.splice(i, 1)
      } catch (error) {
        this.$message.success('删除失败！')
      }
    },
    // 收藏图片
    async collectImg (img) {
      try {
        await switchCollect(img.id, !img.is_collected)
        this.$message.success('操作成功！')
        img.is_collected = !img.is_collected
      } catch (error) {
        this.$message.success('操作失败！')
      }
    },
    // 分页事件
    pageChange (curPage) {
      this.page = curPage
      this.getImages()
    },
    // 切换列表不同状态
    changeStatus () {
      this.getImages()
    },
    // 获取图片列表
    async getImages () {
      const { data: { data } } = await getImages({
        page: this.page,
        per_page: this.per_page,
        collect: this.status
      })
      // 赋值之前添加选择属性
      data.results.forEach((img) => (img.isSelected = false))
      // console.log(status, data)
      this.total = data.total_count
      this.images = data.results
    }
  }
}
</script>

<style lang="less" scoped>
.image-todo {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.image-box {
  position: relative;
  height: 150px;
  margin-bottom: 10px;
  overflow: hidden;
  &:hover {
    .image-act {
      transform: translate3d(0, 0, 0);
    }
  }
  .el-image {
    width: 100%;
    height: 100%;
  }
  .image-act {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 30px;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    text-align: center;
    transition: all 0.2s linear;
    transform: translate3d(0, 30px, 0);
    span {
      flex: 1;
      height: 30px;
      line-height: 30px;
      color: #fff;
      transition: background 0.2s linear;
      cursor: pointer;
      &:hover {
        background: #40a0ffcc;
      }
      &.el-icon-star-on {
        font-size: 22px;
      }
    }
  }
  .image-sel {
    position: absolute;
    left: 45%;
    top: 50px;
    font-size: 30px;
    color: #36e736;
  }
}
.avatar-uploader {
  margin: 0 auto;
  width: 180px;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
